﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using ptp3.Models;
using System.Globalization;

namespace ptp3.Controllers
{
    public class ScrapeController : Controller
    {
        //
        // GET: /Scrape/

        public string Index()
        {
            const string HashPlace = "####################";
            string rawurl = Request.RawUrl;
            string info_hash = rawurl.Split('?').
                Where(st => st.StartsWith("info_hash=")).First()
                .Remove(0, "info_hash=".Count());

            var ms = new MemoryStream();
            for (var i = 0; i < info_hash.Length; i++)
            {
                if (info_hash[i] == '%')
                {
                    ms.WriteByte(
                        byte.Parse(info_hash.Substring(i + 1, 2), NumberStyles.AllowHexSpecifier));
                    i += 2;
                }
                else if (info_hash[i] < 128)
                {
                    ms.WriteByte((byte)info_hash[i]);
                }
            }

            byte[] infoHash = ms.ToArray();
            info_hash = BitConverter.ToString(infoHash).Replace("-", "");

            if (info_hash == null)
                throw new BEException("No info_hash provided.");

            if (info_hash.Length != 40)
            {
                throw new BEException("Invalid info_hash length.");
            }
            
            ptp3Entities ptp3db = new ptp3Entities();
            var ThisTorrent = ptp3db.torrents.Where(t => t.info_hash == info_hash).SingleOrDefault();

            var hashdata = new Dictionary<BEString, IBE> {
					{"complete", (BENumber)ThisTorrent.seeding},
					{"incomplete", (BENumber)ThisTorrent.leeching},
					{"downloaded", (BENumber)ThisTorrent.completed},
				};
            var files = new Dictionary<BEString, IBE> {
					{HashPlace, (BEDict)hashdata}
				};
            BEDict response = new Dictionary<BEString, IBE> {
					{"files", (BEDict)files}
				};

            return response.Dump();
        }
        public class BEException : Exception
        {
            public BEException(string message)
                : base(message)
            {
            }
            public override string ToString()
            {
                BEDict dict = new Dictionary<BEString, IBE> { { "failure reason", (BEString)Message } };
                return dict.Dump();
            }
        }

    }
}
